package com.zlgs.cqyf.vote;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


 
public class TimerTaskListener extends HttpServlet implements ServletContextListener {
	private static final long serialVersionUID = 1L;
       
	private  Timer timer = null;  
   
    public TimerTaskListener() {
        super();
    }

    static class ScannerVoteTask extends TimerTask{

		@Override
		public void run() {
			System.out.println("指向扫描定时任务开始!");
				Connection conn = null;
				JSONArray array = new JSONArray();
				conn =   ConnectionUtil.getConnection();
//				conn = ConnectionPool.getInstance().getConnection();
				Statement statement = null ;
				ResultSet resultSet = null;
				ResultSet subNameResult = null;
				try {
					statement = conn.createStatement();
					resultSet = statement.executeQuery("select * from vote_awards where is_del =0");
					ResultSetMetaData metaData = resultSet.getMetaData();
					while(resultSet.next()) {
						JSONObject obj = new JSONObject();
						for(int i = 0; i < metaData.getColumnCount(); i++){
							String columnLabel = metaData.getColumnLabel(i+1);//获取指定列的别名
							String columnValue = null == resultSet.getObject(columnLabel)?"": resultSet.getObject(columnLabel).toString();//#根据别名,获取数据库中对应的数据 
							obj.put(columnLabel, columnValue);
						 }
						array.add(obj);
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}finally{
					if(null!=statement){
						try {
							statement.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
					if(null!=resultSet){
						try {
							resultSet.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
				}
				
				if(array.size()>0) {
					Iterator<Object> iterator = array.iterator();
					Statement subAwardStateMent = null;
					ResultSet subResult = null;
					Statement updateStatement = null;
					while(iterator.hasNext()) {
						try{
							JSONObject next = (JSONObject)iterator.next();
							Integer awardId =  next.getInteger("id");
							Date startDate = null;
							Date endDate = null;
							
							String startString = next.getString("start_time");
							startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startString);
							String endString = next.getString("end_time");
							endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endString);
							
							Date now = new Date();
							subAwardStateMent = conn.createStatement();
							/*若当前时间大于开始时间并小于结束时间 则将未开始的投票活动/评优展示活动置为已开始*/
							if(checkDateTime(startDate,now) && checkDateTime(now,endDate)) {
								  subResult = subAwardStateMent.executeQuery("select * from vote_awards_subname where awards_id = '"+awardId+"' AND is_del = 0 and status = 0 ");
								  while(subResult.next()) {
									  String subAwardId = subResult.getString("id");
									  updateStatement = conn.createStatement();
									  updateStatement.executeUpdate("update vote_awards_subname  set status  = 1,  msg_status=1 where id = '"+subAwardId+"'");
									  /**发送通知信息，包括 邮件 和 企业微信  **/
									  // TODO
								  }
							}
							/*若当前时间大于 结束时间 则将未开始的投票活动/评优展示活动置为已结束*/
							if(checkDateTime(endDate,now)) {
								subNameResult = subAwardStateMent.executeQuery("select * from vote_awards_subname where awards_id = '"+awardId+"' AND is_del = 0 and status = 1 ");
								while(subNameResult.next()) {
									String subAwardId = subNameResult.getString("id");
									updateStatement = conn.createStatement();
									updateStatement.executeUpdate("update vote_awards_subname  set status  = -1 where id = '"+subAwardId+"'");
								}
							}
						}catch(Exception ex){
							continue;
						}finally{
							
							if(null!=subAwardStateMent){
								try {
									subAwardStateMent.close();
								} catch (SQLException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							if(null!=subResult){
								try {
									subResult.close();
								} catch (SQLException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							if(null!=updateStatement){
								try {
									updateStatement.close();
								} catch (SQLException e) {
									e.printStackTrace();
								}
							}
							if(null!=subNameResult){
								try {
									subNameResult.close();
								} catch (SQLException e) {
									e.printStackTrace();
								}
							}
							
						}
					}
				}
				if(null!=conn){
					try {
						conn.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				System.out.println("指向扫描定时任务结束!    "+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		}
	}
	 
	

 
	/**
	 * 开始时间，结束时间校验
	 * 
	 * @param d1
	 * @param d2
	 * @return
	 */
	private static boolean checkDateTime(Date d1, Date d2) {
		Calendar startInstance = Calendar.getInstance();
		startInstance.setTime(d1);
		Calendar endInstance = Calendar.getInstance();
		endInstance.setTime(d2);
		if (d1.before(d2)) {
			return true;
		} else {
			return false;
		}
	}
	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("listener destoryed " );
		if(null!=timer) {
			timer.cancel();
		}
		System.out.println("listener destoryed end " );
		
	}

	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		 timer = new Timer();  
		
//		 timer.scheduleAtFixedRate(voteTask, 0, 300000);   //任务2 2秒后开始进行重复的固定速率执行（3秒钟重复一次）  
		 //每两分钟扫描一次数据库
	 	long daySpan = 2* 60 * 1000;
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 09:16:00");
        // 首次运行时间
        try {
//            Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));
//            // 如果今天的已经过了 首次运行时间就改为明天
//            if (System.currentTimeMillis() > startTime.getTime()){
//                startTime = new Date(startTime.getTime() + daySpan);
//            }
           
        	// 以每24小时执行一次
            timer.schedule(new ScannerVoteTask(), new Date(), daySpan);
        } catch (Exception e) {
            e.printStackTrace();
        }
		
	}

}
